package highfreq;
// Definition for singly-linked list.
class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }

public class item25 {


    public static ListNode reverseKGroup(ListNode head, int k) {
        ListNode cur ;
        ListNode next ;
        cur=next=head;
        ListNode pre =null;
        int i=0;
        while (i<k)
        {   if(next ==null) return head;
            next=next.next;
            i++;
        }

          pre=  reverse(cur,next);
//          cur = next;

          cur.next = reverseKGroup(next,k);


        return pre;
    }

    private static ListNode reverse(ListNode cur, ListNode next) {
        ListNode pre =null;
        ListNode temp =cur;
        while (cur!=next)
        {
            temp = cur.next;
            cur.next = pre;


            pre = cur;
            cur = temp;
        }
        return pre;
    }

    public static void main(String[] args) {
        ListNode a = new ListNode(1);
        ListNode b = new ListNode(2);
        ListNode c = new ListNode(3);
        ListNode d = new ListNode(4);
        ListNode e = new ListNode(5);
        a.next=b;
        b.next=c;
        c.next =d;
        d.next =e;
        ListNode listNode = reverseKGroup(a, 2);
        System.out.println(listNode.val);

    }

}
